import {
  app,
  shell,
  BrowserWindow,
  Tray,
  nativeImage,
  KeyboardEvent,
  Rectangle,
  globalShortcut
} from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import services from './services/main/services'
import appConfig from '../../package.json'
import openTrayMenu from './services/trayMenu'
import createWindow from './services/common/newWindow'

let appIcon: string, tray: Tray

const createMainWindow = async () => {
  // 任务栏图标

  // 托盘图标
  appIcon = join(__dirname, '../../resources/images/logo-256x256.ico')

  const mainWindow = await createWindow('#/', {
    width: 200,
    height: 80,
    x: 1500,
    y: 200
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // ipcmain 服务
  services({ mainWindow, app })

  // 托盘功能
  tray = new Tray(nativeImage.createFromPath(appIcon))

  // 托盘tip
  tray.setToolTip(appConfig.applicationName)

  app.setName(appConfig.applicationName)

  //  隐藏任务图标
  mainWindow.setSkipTaskbar(true)

  mainWindow.setTitle(appConfig.applicationName)

  tray.on('right-click', (_event: KeyboardEvent, bounds: Rectangle) => {
    const { x, y } = bounds
    openTrayMenu({ x, y })
  })
}
app.whenReady().then(() => {
  electronApp.setAppUserModelId('clock')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createMainWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
  })
})

/**
 * 程序退出前销毁托盘图标
 */
app.on('before-quit', function () {
  tray.destroy()
})
app.on('window-all-closed', () => {
  // 注销所有快捷键
  globalShortcut.unregisterAll()
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
